package xyz.xiangyushui.controller.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xyz.xiangyushui.dao.user.member.MembershipDao;
import xyz.xiangyushui.dao.user.member.MembershipProfileDao;
import xyz.xiangyushui.daoFactory.user.UserDaoFactory;
import xyz.xiangyushui.javaBean.user.Role;
import xyz.xiangyushui.javaBean.user.User;

/**
 * Servlet implementation class RegisterValidater
 */
@WebServlet("/Register")
public class RegisterValidater extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserDaoFactory f;
	private final String emptyWarning = "Incomplete form!";
	private final String diffPwd = "Two Differnt passwords!";
	private final String userExist = "The userName already exists!";
	private MembershipDao membershipDao;
	private MembershipProfileDao mpd;
	
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegisterValidater() {
		super();
		f = new UserDaoFactory();
		membershipDao=new MembershipDao();
		mpd=new MembershipProfileDao();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String passwordRepeat = request.getParameter("password-repeat");
		String msg = validate(userName, password, passwordRepeat);
		System.out.println(msg);
		if (msg.equals("valid")) {
			User u = new User();
			u.setName(userName);
			u.setPwd(password);
			u.setRole(Role.member);
			f.getUserDao().add(u);
			membershipDao.addMember(u.getName());
			mpd.addNewMembershipProfile(u.getName());
			request.getSession(true).setAttribute("user", u);
			request.getSession(true).setAttribute("userName", u.getName());
			request.getRequestDispatcher("/router").forward(request, response);
		} else {
			request.setAttribute("failedMsg", msg);
			request.getRequestDispatcher("/register").forward(request, response);
		}
	}

	private String validate(String userName, String pwd, String pwdRepeat) {
		String result = "valid";
		if ("".equals(userName) || "".equals(pwd) || "".equals(pwdRepeat)) {
			result = emptyWarning;
		} else if (!pwd.equals(pwdRepeat)) {
			result = diffPwd;
		} else {
			User u = new User();
			u.setName(userName);
			if (f.getUserDao().exists(u)) {
				result = userExist;
			}
		}
		return result;
	}

}
